package com.wwz.leetcode;

import com.wwz.common.ListNode;
import org.junit.Test;

/**
 * @Description: 两数相加
 * @create: 2021-09-03 19:04:15
 * @author:wwz
 */
public class LeetCode2 {

    @Test
    public void test() {
        //243
        ListNode l13 = new ListNode(3);
        ListNode listNode1 = new ListNode(4, l13);
        ListNode listNode2 = new ListNode(2, listNode1);

        //564
        ListNode l14 = new ListNode(4);
        ListNode listNode3 = new ListNode(6, l14);
        ListNode listNode4 = new ListNode(5, listNode3);

        addTwoNumbers(listNode2, listNode4);

//        ListNode l1 = new ListNode(9);
//        ListNode l2 = new ListNode(1, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))))))))));
//        addTwoNumbers(l1, l2);


    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 进位
        int carry = 0;
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        while (l1 != null || l2 != null) {

            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int sum = x + y + carry;
            carry = 0;

            int i1 = sum % 10;
            int i2 = sum / 10;
            carry = i2;
            cur.next = new ListNode(i1);
            cur = cur.next;

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }

        }
        if(carry ==1){
            cur.next = new ListNode(1);
        }
        return pre.next;
    }

}
